const state = {
  currentPatient: null // 存储当前患者信息
}

const mutations = {
  SET_CURRENT_PATIENT: (state, patient) => {
    state.currentPatient = patient
    // 同时保存到 localStorage 作为备用
    try {
      if (patient) {
        localStorage.setItem('CURRENT_PATIENT', JSON.stringify(patient))
      } else {
        localStorage.removeItem('CURRENT_PATIENT')
      }
    } catch (e) {
      console.error('Failed to save patient to localStorage:', e)
    }
  },
  CLEAR_CURRENT_PATIENT: (state) => {
    state.currentPatient = null
    try {
      localStorage.removeItem('CURRENT_PATIENT')
    } catch (e) {
      console.error('Failed to remove patient from localStorage:', e)
    }
  }
}

const actions = {
  setCurrentPatient({ commit }, patient) {
    commit('SET_CURRENT_PATIENT', patient)
  },
  clearCurrentPatient({ commit }) {
    commit('CLEAR_CURRENT_PATIENT')
  },
  // 新增：从 localStorage 恢复患者信息
  restorePatientFromStorage({ commit }) {
    try {
      const raw = localStorage.getItem('CURRENT_PATIENT')
      if (raw) {
        const patient = JSON.parse(raw)
        if (patient && (patient.id || patient.patientId)) {
          commit('SET_CURRENT_PATIENT', patient)
          return patient
        }
      }
    } catch (e) {
      console.error('Failed to restore patient from localStorage:', e)
    }
    return null
  }
}

const getters = {
  currentPatient: state => state.currentPatient,
  currentPatientId: state => state.currentPatient?.id || null,
  // 新增：增强的 patientId getter，包含 localStorage 备用
  robustPatientId: (state) => {
    // 优先从 Vuex state 获取
    if (state.currentPatient?.id) {
      return state.currentPatient.id
    }

    // 备用：从 localStorage 获取
    try {
      const raw = localStorage.getItem('CURRENT_PATIENT')
      if (raw) {
        const patient = JSON.parse(raw)
        return patient?.id || patient?.patientId || null
      }
    } catch (e) {
      console.error('Failed to get patient ID from localStorage:', e)
    }

    return null
  },
  // 新增：获取患者数据的备用方法
  patientFallbackData: () => {
    try {
      const raw = localStorage.getItem('CURRENT_PATIENT')
      return raw ? JSON.parse(raw) : null
    } catch (e) {
      console.error('Failed to get patient fallback data:', e)
      return null
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
